package com.fintech.third.service.facerecog;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fintech.common.service.BaseServiceImpl;
import com.fintech.common.util.RedisUtils;
import com.fintech.third.constant.ThirdMethodConstants;
import com.fintech.third.constant.ThirdProductChannelConstant;
import com.fintech.third.constant.ThirdProductConstant;
import com.fintech.third.dao.EdcIdnumberOcrResultMapper;
import com.fintech.third.dao.FaceRecognitionMapper;
import com.fintech.third.dao.ThirdProductChannelMappper;
import com.fintech.third.model.EdcIdnumberOcrResult;
import com.fintech.third.model.ThirdProductChannel;
import com.fintech.third.model.ThirdProperties;
import com.fintech.third.model.facerecog.FaceCompareResponse;
import com.fintech.third.model.facerecog.FaceRecognition;
import com.fintech.third.model.facerecog.IdCardOcrResult;
import com.fintech.third.model.facerecog.NumberVerfication;
import com.fintech.third.utils.ThirdPropertiesInitUtil;
import com.marvels.common.utils.MarvelsLogUtil;

import net.sf.json.JSONObject;

@Service("FaceRecognition")
public class FaceRecognitionImpl extends BaseServiceImpl implements FaceRecognitionService {
	@Autowired
	private ThirdProductChannelMappper thirdProductChannelMappper;
	@Autowired
	private FaceRecognitionMapper faceRecognitionMapper;
	@Autowired
	private ShangTService shangTService;
	@Autowired
	private YiTuService yiTuService;
	@Autowired
	private OpenViewSevice openViewSevice;
	
	@Autowired
	private EdcIdnumberOcrResultMapper resultMapper;
	
	@Override
	public FaceCompareResponse idNumberVerification(Map<String, String> map) {
		String loanId = map.get("loanId");
		NumberVerfication numberVerfication = new NumberVerfication();
		FaceCompareResponse faceCompareResponse = new FaceCompareResponse();
		String channelCode = map.get("channelCode");
		String id_number = map.get("idNumber");
		String user_name = map.get("userName");
		Map<String, String> shangTMap = new HashMap<String, String>();
		shangTMap.put("id_number", id_number);
		shangTMap.put("user_name", user_name);
		shangTMap.put("loanId", loanId);
		Map<String, String> yiTuMap = new HashMap<String, String>();
		yiTuMap.put("name", user_name);
		yiTuMap.put("citizen_id", id_number);
		yiTuMap.put("loanId", loanId);
		if (StringUtils.isNotEmpty(channelCode)
				&& channelCode.equals(ThirdProductChannelConstant.SHANGTANG.getCode())) {// 商汤通道
			faceCompareResponse = shangTService.idVerification(shangTMap);
		} else if (StringUtils.isNotEmpty(channelCode)
				&& channelCode.equals(ThirdProductChannelConstant.YITU.getCode())) {// 依图通道
			faceCompareResponse = yiTuService.idCardVerification(yiTuMap);
		} else {
			List<ThirdProductChannel> thirdProductChannelList = new ArrayList<ThirdProductChannel>();
			thirdProductChannelList = thirdProductChannelMappper
					.queryThirdProductChannel(ThirdProductConstant.FACERECOGNITION.getCode());

			for (ThirdProductChannel thirdProductChannel : thirdProductChannelList) {
				if (thirdProductChannel.getCode().equals(ThirdProductChannelConstant.SHANGTANG.getCode())) {
					channelCode = ThirdProductChannelConstant.SHANGTANG.getCode();
					faceCompareResponse = shangTService.idVerification(shangTMap);
					break;
				} else if (thirdProductChannel.getCode().equals(ThirdProductChannelConstant.YITU.getCode())) {
					channelCode = ThirdProductChannelConstant.YITU.getCode();
					faceCompareResponse = yiTuService.idCardVerification(yiTuMap);
					break;
				}
			}
		}
		numberVerfication.setChannelCode(channelCode);
		numberVerfication.setIdNumber(id_number);
		numberVerfication.setLoanId(loanId);
		numberVerfication.setName(user_name);
		numberVerfication.setUpdatedBy("sys");
		numberVerfication.setCreatedBy("sys");
		numberVerfication.setUpdatedDate(new Date());
		numberVerfication.setIsTrue(faceCompareResponse.isTrue());
		faceRecognitionMapper.insertNumberVerfication(numberVerfication);

		String resultLog = "";
		if (faceCompareResponse.getErrorCode() == 0) {
			resultLog = "1";
		} else {
			resultLog = "-1";
		}
		if (faceCompareResponse.getChannelCode().equals(ThirdProductChannelConstant.YITU.getCode())) {
			saveCallCountLog(loanId, ThirdMethodConstants.YT0001, resultLog, faceCompareResponse.getChannelCode(),
					"依图身份证号姓名验证");
		} else if (faceCompareResponse.getChannelCode().equals(ThirdProductChannelConstant.SHANGTANG.getCode())) {
			saveCallCountLog(loanId, ThirdMethodConstants.ST0001, resultLog, faceCompareResponse.getChannelCode(),
					"商汤身份证号姓名验证");
		}

		return faceCompareResponse;
	}

	@Override
	public FaceCompareResponse faceComparison(Map<String, String> map) {
		FaceCompareResponse faceCompareResponse = new FaceCompareResponse();
		FaceRecognition faceRecognition = new FaceRecognition();
		String loanId = map.get("loanId");
		String channelCode = map.get("channelCode");
		String id_number = map.get("idNumber");
		String user_name = map.get("userName");
		String image_base64 = map.get("image_base64");
		String delta=map.get("delta");//旷视sdk中返回的
		String productType = map.get("productType");//产品类型，1.线上，2.线下
		Map<String, String> shangTMap = new HashMap<String, String>();
		shangTMap.put("id_number", id_number);
		shangTMap.put("user_name", user_name);
		shangTMap.put("image_base64", image_base64);
		shangTMap.put("loanId", loanId);
		Map<String, String> yiTuMap = new HashMap<String, String>();
		yiTuMap.put("query_image_content", image_base64);
		yiTuMap.put("citizen_id", id_number);
		yiTuMap.put("name", user_name);
		yiTuMap.put("loanId", loanId);
		Map<String, String> openViewMap = new HashMap<String, String>();
		openViewMap.put("query_image_content", image_base64);
		openViewMap.put("idcardNumber", id_number);
		openViewMap.put("idcardName", user_name);
		openViewMap.put("delta", delta);
		openViewMap.put("loanId", loanId);
		openViewMap.put("image_env",map.get("image_env"));//用于假脸判定，请传MegLive SDK返回的用作云端假脸攻击判定的照片
		String faceLoanId="face"+loanId;
		// 兼容整合后因为redis反序列化问题
		String faceLoanIdCount = null;
		try {
			faceLoanIdCount = RedisUtils.getInstance().get(faceLoanId);
		} catch (Exception e) {
			RedisUtils.getInstance().del(faceLoanIdCount);
		}
		ThirdProperties thirdProperties=ThirdPropertiesInitUtil.getThirdProperties(); 
		String failTimes = thirdProperties.getFace_fail_frequency();
		if(StringUtils.equals("1", productType)){
			failTimes = thirdProperties.getFace_fail_frequency2();//线上为6次
		}
		MarvelsLogUtil.getInstance().info("===========人脸对比ocr识别loanId:"+loanId+",调用次数:"+faceLoanIdCount+",配置参数：="+failTimes);
		if(StringUtils.isNotEmpty(faceLoanIdCount) && Integer.parseInt(faceLoanIdCount) >= Integer.parseInt(failTimes)){//超过三次则为失败
		//if(StringUtils.isNotEmpty(faceLoanIdCount) && Integer.parseInt(faceLoanIdCount) >= 3){//超过三次则为失败
			MarvelsLogUtil.getInstance().info("===========人脸对比ocr识别超过三次，直接拒绝loanId:"+loanId);
			faceCompareResponse.setErrorCode(-10);
			faceCompareResponse.setErrorMsg("人脸对比ocr识别失败");
			RedisUtils.getInstance().del(faceLoanId);
			return faceCompareResponse;
		}
		if (!StringUtils.isEmpty(channelCode) && channelCode.equals(ThirdProductChannelConstant.SHANGTANG.getCode())) {// 商汤通道
			faceCompareResponse = shangTService.faceAlignment(shangTMap);
		} else if (!StringUtils.isEmpty(channelCode)
				&& channelCode.equals(ThirdProductChannelConstant.YITU.getCode())) {// 依图通道
			faceCompareResponse = yiTuService.comparisonService(yiTuMap);
		} else if (!StringUtils.isEmpty(channelCode)
				&& channelCode.equals(ThirdProductChannelConstant.KUANGSHI.getCode())) {// 旷视通道
			faceCompareResponse = openViewSevice.openViewFaceAlignmentOcr(openViewMap);
		} else {
			List<ThirdProductChannel> thirdProductChannelList = new ArrayList<ThirdProductChannel>();
			thirdProductChannelList = thirdProductChannelMappper
					.queryThirdProductChannel(ThirdProductConstant.FACERECOGNITION.getCode());

			for (ThirdProductChannel thirdProductChannel : thirdProductChannelList) {
				if (thirdProductChannel.getCode().equals(ThirdProductChannelConstant.SHANGTANG.getCode())) {
					channelCode = ThirdProductChannelConstant.SHANGTANG.getCode();
					faceCompareResponse = shangTService.faceAlignment(shangTMap);
					break;
				} else if (thirdProductChannel.getCode().equals(ThirdProductChannelConstant.YITU.getCode())) {
					channelCode = ThirdProductChannelConstant.YITU.getCode();
					faceCompareResponse = yiTuService.comparisonService(yiTuMap);
					break;
				}else if (thirdProductChannel.getCode().equals(ThirdProductChannelConstant.KUANGSHI.getCode())) {
					channelCode = ThirdProductChannelConstant.KUANGSHI.getCode();
					faceCompareResponse = openViewSevice.openViewFaceAlignmentOcr(openViewMap);
					break;
				}
			}
		}
		faceRecognition.setChannelCode(channelCode);
		faceRecognition.setIdNumber(id_number);
		faceRecognition.setLoanId(loanId);
		faceRecognition.setName(user_name);
		faceRecognition.setCreatedBy("sys");
		faceRecognition.setUpdatedBy("sys");
		faceRecognition.setUpdatedDate(new Date());
		faceRecognition.setScore(faceCompareResponse.getScore());
		faceRecognitionMapper.insertFaceRecognition(faceRecognition);

		faceCompareResponse.setChannelCode(channelCode);
		String resultLog = "";
		if (faceCompareResponse.getErrorCode() == 0) {
			resultLog = "1";
		} else {
			resultLog = "-1";
		}
		if(StringUtils.isEmpty(faceLoanIdCount)){
			RedisUtils.getInstance().set(faceLoanId, "1");
		}else{
			faceLoanIdCount=(Integer.parseInt(faceLoanIdCount)+1)+"";
			RedisUtils.getInstance().set(faceLoanId,faceLoanIdCount);
		}
		if (faceCompareResponse.getChannelCode().equals(ThirdProductChannelConstant.YITU.getCode())) {
			saveCallCountLog(loanId, ThirdMethodConstants.YT0002, resultLog, faceCompareResponse.getChannelCode(),
					"依图人脸对比");
		} else if (faceCompareResponse.getChannelCode().equals(ThirdProductChannelConstant.SHANGTANG.getCode())) {
			saveCallCountLog(loanId, ThirdMethodConstants.ST0002, resultLog, faceCompareResponse.getChannelCode(),
					"商汤人脸对比");
		}else if(faceCompareResponse.getChannelCode().equals(ThirdProductChannelConstant.KUANGSHI.getCode())) {
			saveCallCountLog(loanId, ThirdMethodConstants.KUANGSHI003, resultLog, faceCompareResponse.getChannelCode(),
					"旷视人脸对比");
		}

		return faceCompareResponse;
	}

	@Override
	public FaceCompareResponse idCardIdentification(Map<String, String> map) {
		MarvelsLogUtil.getInstance().info(">>>>>身份证识别开始");
		String loanId = map.get("loanId");
		FaceCompareResponse faceCompareResponse=new FaceCompareResponse();
		String image_base64 = map.get("imageContent");
		String channelCode=map.get("channelCode");
		Map<String, String> shangTMap = new HashMap<String, String>();
		shangTMap.put("base64File", image_base64);
		shangTMap.put("freshVersion",map.get("freshVersion"));
		shangTMap.put("loanId", loanId);
		Map<String, String> yiTuMap = new HashMap<String, String>();
		yiTuMap.put("imageContent", image_base64);
		yiTuMap.put("ocrMode", map.get("ocrMode"));
		yiTuMap.put("freshVersion", map.get("freshVersion"));
		yiTuMap.put("loanId", loanId);
		Map<String, String> openViewMap = new HashMap<String, String>();
		openViewMap.put("imageContent", image_base64);
		openViewMap.put("freshVersion", map.get("freshVersion"));
		openViewMap.put("loanId", loanId);
//		if (!StringUtils.isEmpty(channelCode) && channelCode.equals(ThirdProductChannelConstant.SHANGTANG.getCode())) {// 商汤通道
//			faceCompareResponse = shangTService.stIdCardIdentification(shangTMap);
//		} else if (!StringUtils.isEmpty(channelCode)
//				&& channelCode.equals(ThirdProductChannelConstant.YITU.getCode())) {// 依图通道
//			faceCompareResponse = yiTuService.ocrUniversalInterface(yiTuMap);
//		} else {
//			List<ThirdProductChannel> thirdProductChannelList = new ArrayList<ThirdProductChannel>();
//			thirdProductChannelList = thirdProductChannelMappper
//					.queryThirdProductChannel(ThirdProductConstant.FACERECOGNITION.getCode());
//
//			for (ThirdProductChannel thirdProductChannel : thirdProductChannelList) {
//				if (thirdProductChannel.getCode().equals(ThirdProductChannelConstant.SHANGTANG.getCode())) {
//					channelCode = ThirdProductChannelConstant.SHANGTANG.getCode();
//					faceCompareResponse = shangTService.stIdCardIdentification(shangTMap);
//					break;
//				} else if (thirdProductChannel.getCode().equals(ThirdProductChannelConstant.YITU.getCode())) {
//					channelCode = ThirdProductChannelConstant.YITU.getCode();
//					faceCompareResponse = yiTuService.ocrUniversalInterface(yiTuMap);
//					break;
//				}
//			}
//		}
		if (!StringUtils.isEmpty(channelCode) && channelCode.equals(ThirdProductChannelConstant.SHANGTANG.getCode())) {// 商汤通道
			faceCompareResponse = shangTService.stIdCardIdentification(shangTMap);
		}else if (!StringUtils.isEmpty(channelCode) && channelCode.equals(ThirdProductChannelConstant.KUANGSHI.getCode())) {// 旷视通道
			faceCompareResponse = openViewSevice.openViewIdCardOcr(yiTuMap);
		} else {// 依图通道
			faceCompareResponse = yiTuService.ocrUniversalInterface(yiTuMap);
		}
		faceCompareResponse.setChannelCode(channelCode);
		//持久化识别信息
		try {
			if(null!=faceCompareResponse.getOcrResult()){
				IdCardOcrResult result=(IdCardOcrResult)faceCompareResponse.getOcrResult();
				EdcIdnumberOcrResult ocrResult=new EdcIdnumberOcrResult();
				ocrResult.setAddress(result.getAddress());
				ocrResult.setNation(result.getNation());
				ocrResult.setAuthority(result.getAuthority());
				ocrResult.setNumber(result.getNumber());
				ocrResult.setCreatedBy("system");
				ocrResult.setCreatedDate(new Date());
				ocrResult.setDay(result.getDay());
				ocrResult.setGender(result.getGender());
				ocrResult.setMonth(result.getMonth());
				ocrResult.setName(result.getName());
				ocrResult.setSide(result.getSide());
				ocrResult.setTimelimit(result.getTimelimit());
				ocrResult.setType(result.getType());
				ocrResult.setYear(result.getYear());
				ocrResult.setUpdatedBy("system");
				ocrResult.setChannelCode(channelCode);
				ocrResult.setUpdatedDate(new Date());
				resultMapper.insertSelective(ocrResult);
			}
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>>>>>>>身份证识别持久化异常:",e);
		}
		MarvelsLogUtil.getInstance().info("===============身份证识别返回参数:"+JSONObject.fromObject(faceCompareResponse));
		return faceCompareResponse;
	}

	@Override
	public FaceCompareResponse bankCardIdentification(Map<String, String> map) {
		MarvelsLogUtil.getInstance().info("===============银行卡识别开始");
		String loanId = map.get("loanId");
		FaceCompareResponse faceCompareResponse=new FaceCompareResponse();
		String base64File=map.get("base64File");
		String channelCode=map.get("channelCode");
		String freshVersion=map.get("freshVersion");
		Map<String, String> shangTMap = new HashMap<String, String>();
		shangTMap.put("base64File", base64File);
		shangTMap.put("freshVersion",freshVersion);
		shangTMap.put("loanId", loanId);
		Map<String, String> openViewMap = new HashMap<String, String>();
		openViewMap.put("imageContent", base64File);
		openViewMap.put("freshVersion",freshVersion);
		openViewMap.put("loanId", loanId);
//		if (!StringUtils.isEmpty(channelCode) && channelCode.equals(ThirdProductChannelConstant.KUANGSHI.getCode())) {// 商汤通道
//			faceCompareResponse = openViewSevice.openViewBankCardOcr(openViewMap);
//		} else {// 商汤通道
//			faceCompareResponse = shangTService.bankCardIdentification(openViewMap);
//		}
		faceCompareResponse = shangTService.bankCardIdentification(shangTMap);
		faceCompareResponse.setChannelCode(channelCode);
		MarvelsLogUtil.getInstance().info("===============银行卡识别返回参数:"+JSONObject.fromObject(faceCompareResponse));
		return faceCompareResponse;
	}

}
